import React, {Component, Fragment} from 'react'
import {Layout, Row, Col, Icon, Affix, Menu, BackTop, Button} from 'antd'
import Link from 'umi/link'
import Exception from '@/components/Exception'
import DocumentTitle from 'react-document-title'
import styles from './DocsLayout.less'
import {get} from '@/utils'
import MobileMenu from 'rc-drawer'
import {enquireScreen} from 'enquire-js'
import router from 'umi/router'
import {connect} from 'dva'
import {injectIntl} from 'react-intl'
import {getLocale, setLocale, FormattedMessage} from 'umi/locale'

let isMobile = false
enquireScreen(b => {
  isMobile = b
})
const {Header, Footer} = Layout

@connect(({content}) => ({project: content.project.data}))
class DocsLayout extends Component {
  state = {
    isMobile,
    openKeys: [],
    selectedKeys: ['/?page=home'],
    menus: [],
  }

  componentDidMount() {
    const {dispatch} = this.props
    dispatch({type: 'content/getProjectAction'})
    const page = get(this.props, 'location.query.page')
    if (page) {
      console.info(page)
      this.setState({selectedKeys: ['/?page=' + page]})
    }
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    const page = get(this.props, 'location.query.page')
    const selectKey = get(this.state, 'selectedKeys.0')
    const actionKey = '/?page=' + page
    if (get(prevProps, 'location.query.page') !== page && selectKey !== actionKey) {
      this.setState({selectedKeys: [actionKey]})
    }
  }

  openSubMenu = (openKeys) => {
    openKeys.length > 1 && openKeys.shift()
    this.setState({openKeys})
  }

  handleLangChange = () => {
    console.info('language', getLocale())
    if (getLocale() === 'en-US') {
      setLocale('zh-CN', true)
    } else {
      setLocale('en-US', true)
    }

  }

  /**
   * 菜单点击
   *
   * @param key
   */
  handleMenuClick = ({key}) => {
    if (key.startsWith('/')) {
      this.setState({
        selectedKeys: [key],
      })
      return router.push(key)
    }

    if (key.startsWith('http://') || key.startsWith('https://')) {
      window.open(key, '_blank')
    }
  }

  renderMenus = items => {
    return items.map(item => {
      const {title, children} = item
      if (Array.isArray(children) && children.length > 0) {
        return <Menu.SubMenu key="sub1" title={<FormattedMessage id={title}/>}>
          {this.renderMenus(children)}
        </Menu.SubMenu>
      } else {
        return <Menu.Item key={item.url}><FormattedMessage id={title}/></Menu.Item>
      }
    })
  }

  getMenuItems = () => {
    const {openKeys, selectedKeys} = this.state
    const menus = get(this.props.project, 'menus', []) || []
    return (menus && Array.isArray(menus) && menus.length > 0 ? (
        <Menu
          className="aside-container menu-site"
          openKeys={openKeys}
          selectedKeys={selectedKeys}
          mode="inline"
          onOpenChange={this.openSubMenu}
          onClick={this.handleMenuClick}
        >
          {this.renderMenus(menus)}
        </Menu>
      ) : (
        <div className={styles.emptyMenu}>
          <Icon type="smile" style={{fontSize: 20}}/>
          <p>空空如也</p>
        </div>
      )
    )
  }

  render() {
    const {isMobile, selectedKeys} = this.state
    const {project, error, children} = this.props
    const title = get(project, 'title') || 'title'
    const topMenus = get(project, 'top_menus', []) || []
    const topMenuMaps = get(project, 'top_menus_map', {}) || {}
    const actionMenu = get(selectedKeys, 0, '/?page=home') || '/?page=home'
    const topAction = get(topMenuMaps, actionMenu) ? actionMenu : '/?page=home'
    const menuChild = this.getMenuItems()
    return (
      <DocumentTitle title={'Laravel-Repository 文档'}>
        <Layout>
          {error ? (
            <Exception
              style={{background: '#fff'}}
              type="403"
              title="Sorry!"
              desc="您没有权限访问该文档"
              backText="返回主页"
            />
          ) : (
            <Fragment>
              <Header className={styles.header}>
                <Row>
                  <Col xxl={4} xl={5} lg={5} md={5} sm={24} xs={24}
                       style={{overflow: 'hidden', textOverflow: 'ellipsis'}}>
                    <span className={styles.logo} title={<FormattedMessage id={title}/>}>
                      <Link to={get(project, 'home', '/')}>
                        {get(project, 'logo') && <img
                          src={project.logo}
                          alt="logo" width="32"
                          height="32"
                          style={{borderRadius: '50%'}}/>}
                      </Link>
                      <FormattedMessage id={title}/>
                    </span>
                  </Col>
                  <Col xxl={20} xl={19} lg={19} md={19} sm={0} xs={0}>
                    <div style={{float: 'right', marginRight: 24}}>
                      <Button size="small" onClick={this.handleLangChange} className={styles['header-lang-button']}>
                        <FormattedMessage id="change.lang"/>
                      </Button>
                      <Menu mode={'horizontal'}
                            className={styles.menu}
                            onClick={this.handleMenuClick}
                            selectedKeys={[topAction]}
                      >
                        {this.renderMenus(topMenus)}
                      </Menu>
                    </div>
                  </Col>
                </Row>
              </Header>
              <Layout style={{background: '#fff'}}>
                <div className="main-wrapper">
                  <Row>
                    {isMobile ? (
                      <MobileMenu
                        iconChild={[<Icon type="menu-unfold"/>, <Icon type="menu-fold"/>]}
                        key="Mobile-menu"
                        wrapperClassName="drawer-wrapper"
                      >
                        {menuChild}
                      </MobileMenu>
                    ) : (
                      <Col xxl={4} xl={5} lg={6} md={24} sm={24} xs={24} className="main-menu">
                        <Affix>
                          <section className="main-menu-inner">{menuChild}</section>
                        </Affix>
                      </Col>
                    )}
                    <Col xxl={20} xl={19} lg={18} md={24} sm={24} xs={24}>
                      {children}
                      <BackTop/>
                      <Footer
                        style={{
                          padding: '0 0 15px 0',
                          textAlign: 'center',
                          background: '#fff',
                        }}
                      >
                        Copyright &copy; 2019 <a href={get(project, 'home', '/')}>
                        <FormattedMessage id="system.name" defaultMessage={'Documentation System'}/>
                      </a>
                      </Footer>
                    </Col>
                  </Row>
                </div>
              </Layout>
            </Fragment>
          )
          }
        </Layout>
      </DocumentTitle>
    )
  }
}

export default injectIntl(DocsLayout)
